package com.song.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.Dto.UserDto;
import com.song.base.exception.HeaderException;
import com.song.base.util.JwtTemplate;
import com.song.base.util.RedisKeys;
import com.song.domain.Tuser;
import com.song.mappers.TuserMapper;
import com.song.service.TuserService;
import com.song.util.UserState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author Song
 * @since 2022-12-19
 */
@Service
@Slf4j
public class TuserServiceImpl extends ServiceImpl<TuserMapper, Tuser> implements TuserService {
    @Resource
    private TuserMapper tuserMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private JwtTemplate jwtTemplate;

    @Override
    public Tuser queryUserByEmail(String email) {
        QueryWrapper<Tuser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mailbox",email);
        return tuserMapper.selectOne(queryWrapper);
    }

    @Override
    public Tuser queryUserByTel(String tel) {
        QueryWrapper<Tuser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tel",tel);
        return tuserMapper.selectOne(queryWrapper);
    }
    @Override
    public String sendEmail(String emailNo,int type){
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String key="";
        String msgSend="";//待填充验证码的提示文字
        if (type==2) {
            QueryWrapper<Tuser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mailbox",emailNo);
            Tuser tuser = tuserMapper.selectOne(queryWrapper);
            if (tuser==null){
                return "邮箱未注册请先注册欧";
            }
            key=RedisKeys.USER_EMAIL_LOGIN;
            msgSend="尊敬的用户你好,你正在使用邮箱登录我们的系统,登录验证码为checkCode,制作不易请转我二佰,谢谢";
        }else if (type==1){
            key=RedisKeys.USER_EMAIL_CHECK;
            msgSend="尊敬的用户你好,你正在使用邮箱注册我们的系统,注册验证码为checkCode,制作不易请转我二佰,谢谢";
        }
        if (key.length()>0){
            String checkR = opsForValue.get(key + emailNo);
            if(StringUtils.isBlank(checkR)) {
                //发送邮件配置
                try {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(UserState.SEND_EMAIL);
                    message.setTo(emailNo);
                    message.setSubject(UserState.SUBJECT_EMAIL);
                    Random random = new Random();
                    int anInt = 100000 + random.nextInt(899999);
                    //1 + random.nextInt(999999)
                    message.setText(msgSend.replace("checkCode",anInt+""));
                    mailSender.send(message);
                    //redis记录验证码
                    opsForValue.set(key + emailNo, anInt + "");
                    stringRedisTemplate.expire(key + emailNo, 300, TimeUnit.SECONDS);
                    return "发送成功，验证码五分钟后过期注意查收";
                }catch (HeaderException e){
                    log.info(""+e);
                    return "邮箱未找到或其他未知异常";
                }
            }
            return "短时间请勿重复发送";
        }
        return "未知异常";
    }
    @Override
    public UserDto login(Tuser tuser){
        //登录的用户信息dto查询
        UserDto userDto = new UserDto();
        //生成token
        String token = tokenCreate(tuser.getId(), tuser.getCname());
        userDto.setToken(token);
        BeanUtils.copyProperties(tuser,userDto);
        //将用户信息存入redis
        redisAdd(tuser);
        return userDto;
    }
    /*
    token生成方法
     */
    private String tokenCreate(Integer userId,String userName){
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId", userId);
        maps.put("username", userName);
        return jwtTemplate.createJwt(maps);
    }
    /*
    用户账户信息存入redis方法
     */
    private void redisAdd(Tuser tuser){
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //在redis里面存入该账号所对应的信息
        if(tuser.getMailbox()!=null)opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "email", tuser.getMailbox());
        if(tuser.getPassword()!=null)opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "password", tuser.getPassword());
        opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "status", tuser.getState()+"");
        if(tuser.getUserPower()!=null)opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "UserPower", tuser.getUserPower()+"");

//        opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "score", userLoginDto.getUserScore().toString());
//        opsForHash.put(RedisKeys.USER_AUTH_USER+tuser.getId(), "money", userLoginDto.getUserMoney().toString());
        stringRedisTemplate.expire(RedisKeys.USER_AUTH_USER+tuser.getId(), jwtTemplate.getJc().getExpire(), TimeUnit.MINUTES);
    }
}
